package com.yer.note.activity;

import static com.yer.note.entity.User.user;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.yer.note.R;
import com.yer.note.entity.Diary;
import com.yer.note.entity.User;
import com.yer.note.entity.Weather;
import com.yer.note.utils.BaseUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class KeepDiaryActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText diaryInputView;
   // private ImageView addPicBtn;
    private ImageView loadLocationBtn;
    private ImageView loadWeatherBtn;
    private ImageView addLabelBtn;
    private ImageView addDateBtn;
    private TextView locationView;
    private TextView weatherView;
    private TextView labelView;
    private TextView dateView;
    Diary diary;
    String diaryuuid;;
   // ArrayList<Uri> imageSrcList;
    boolean isModify;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_keep_diary,menu);
        return true;
    }
    private void initToolbar(){
        Toolbar toolbar = findViewById(R.id.keep_diary_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(null!=actionBar){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("日记编辑");
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.toolbar_diary_send:{
                if(isModify){
                    diary.delete();
                }
                String text = diaryInputView.getText().toString();
                if(text.length()==0){
                    String news = "您还未编辑日记内容";
                    BaseUtils.shortTipInCoast(KeepDiaryActivity.this,news);
                }
                String time = dateView.getText().toString();
                if(dateView.getText().toString()==""){
                    Date date = new Date();//dd-MM-yyyy
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    time = formatter.format(date);
                }
                String location = locationView.getText().toString();
                String label = labelView.getText().toString();
                String weather = weatherView.getText().toString();
                String uuid = BaseUtils.randomUUID();
                Diary diary = new Diary(text,weather,label,location,time,uuid,user.getMyuuid());
                diary.save();
                System.out.println("存储了一天条日记信息：");
                System.out.println(diary);
                finish();
                break;
            }
            case android.R.id.home:{
                System.out.println("返回上一界面");
                finish();
                break;
            }


        }
        return super.onOptionsItemSelected(item);
    }



    public void initView(){
        diaryInputView = findViewById(R.id.keep_diary_input);
       // addPicBtn = findViewById(R.id.keep_diary_btn_image);
        addLabelBtn = findViewById(R.id.keep_diary_btn_label);
        loadLocationBtn = findViewById(R.id.keep_diary_btn_location);
        loadWeatherBtn = findViewById(R.id.keep_diary_btn_weather);
        addDateBtn = findViewById(R.id.keep_diary_btn_date);
        locationView = findViewById(R.id.keep_diary_location);
        weatherView = findViewById(R.id.keep_diary_weather);
        labelView = findViewById(R.id.keep_diary_label);
        dateView = findViewById(R.id.keep_diary_date);
    }
    public void bindListener(){
        locationView.setOnClickListener(this);
        weatherView.setOnClickListener(this);
        labelView.setOnClickListener(this);
        dateView.setOnClickListener(this);
       // addPicBtn.setOnClickListener(this);
        addLabelBtn.setOnClickListener(this);
        loadLocationBtn.setOnClickListener(this);
        loadWeatherBtn.setOnClickListener(this);
        addDateBtn.setOnClickListener(this);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_keep_diary);
        isModify = false;
        Intent intent = getIntent();
        diaryuuid = intent.getStringExtra("diaryUUid");
        System.out.println(diaryuuid);
        initToolbar();
        initView();
        if(!diaryuuid.equals("")){
            isModify = true;
            List<Diary> diaries = Diary.listAll(Diary.class);
            for (Diary diary : diaries) {
                if(diary.getdiaryuuid().equals(diaryuuid)){
                    this.diary = diary;
                    diaryInputView.setText(diary.getContext());
                    labelView.setText(diary.getLabel());
                    weatherView.setText(diary.getWeather());
                    dateView.setText(diary.getTime());
                    locationView.setText(diary.getLocation());
                }
            }
        }
        bindListener();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /*case R.id.keep_diary_btn_image:
            case R.id.keep_diary_btn_image_tip:{
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 2);
                break;
            }*/
            case R.id.keep_diary_weather:
            case R.id.keep_diary_btn_weather:{
                android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(KeepDiaryActivity.this);
                dialog.setTitle("暂时不支持读取当地天气信息，请手动选择");
                String[] items = {Weather.WEATHER_CLOUDY,Weather.WEATHER_RAIN,
                        Weather.WEATHER_SUNNY,Weather.WEATHER_HOT,Weather.WEATHER_OVERCAST,
                        Weather.WEATHER_SNOW,Weather.WEATHER_HAIL,"自定义"};
                dialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if("自定义".equals(items[which])){
                            android.app.AlertDialog.Builder dialog2 = new android.app.AlertDialog.Builder(KeepDiaryActivity.this);
                            dialog2.setTitle("手动输入天气");
                            dialog2.setMessage("15字符以内");
                            EditText editText = new EditText(KeepDiaryActivity.this);
                            editText.setBackgroundResource(R.drawable.background_input);
                            editText.setMinLines(4);
                            editText.setMaxLines(4);
                            editText.setGravity(Gravity.START);
                            editText.setHint("天气情况");
                            editText.setPadding(30,10,30,10);
                            dialog2.setView(editText);
                            dialog2.setCancelable(false);
                            dialog2.setPositiveButton("添加", (dialog3, which2) -> {
                                String s = editText.getText().toString();
                                if(s.length()>15){
                                    BaseUtils.longTipInCoast(KeepDiaryActivity.this,"都说了自定义天气只能15字符以内咯");
                                }else{
                                    weatherView.setText(s);
                                }
                            });
                            dialog2.setNegativeButton("取消",null);
                            dialog2.show();
                        }else{
                            weatherView.setText(items[which]);
                        }
                    }
                });
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", null);
                dialog.setNegativeButton("取消", (dialog12, which) -> weatherView.setText(""));
                dialog.show();
                break;
            }
            case R.id.keep_diary_label:
            case R.id.keep_diary_btn_label:{
                android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(KeepDiaryActivity.this);
                dialog.setTitle("请输入标签");
                dialog.setMessage("可输入多个标签，但请用英文#隔开。\ne.g:#美食##周末#");
                EditText editText = new EditText(KeepDiaryActivity.this);
                editText.setBackgroundResource(R.drawable.background_input);
                editText.setMinLines(4);
                editText.setMaxLines(4);
                editText.setGravity(Gravity.START);
                editText.setHint("空输入视为删除原有输入");
                editText.setPadding(30,10,30,10);
                dialog.setView(editText);
                dialog.setCancelable(false);
                dialog.setPositiveButton("添加", (dialog1, which) -> {
                    String labelStr = editText.getText().toString();
                    labelStr = labelStr.trim();
                    int num = 0;
                    for (char c : labelStr.toCharArray()) {
                        if(c == '#'){
                            num++;
                        }
                    }
                    boolean flag = (num%2==0 && num!=0);
                    if(labelStr.length()<=30 && flag){
                        labelView.setText(labelStr);
                    }else{
                        BaseUtils.longTipInCoast(v.getContext(),"标签总字符数不超过30,格式必须正确");
                    }
                });
                dialog.setNegativeButton("取消",null);
                dialog.show();
                break;
            }
            case R.id.keep_diary_date:
            case R.id.keep_diary_btn_date:{
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePickerDialog = new DatePickerDialog(
                        KeepDiaryActivity.this,
                        (view, year, month, dayOfMonth) -> {

                            new TimePickerDialog(KeepDiaryActivity.this, new TimePickerDialog.OnTimeSetListener() {
                                @Override
                                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                    if(month>9&&dayOfMonth>9){
                                        String dateStr = year + "-" + (month + 1) + "-" + dayOfMonth + " " + hourOfDay + ":" + minute + ":" + "00";
                                        dateView.setText(dateStr);
                                    }else if(month>9&&dayOfMonth<=9){
                                        String dateStr = year + "-" + (month + 1) + "-0" + dayOfMonth + " " + hourOfDay + ":" + minute + ":" + "00";
                                        dateView.setText(dateStr);
                                    }else if(month<=9&&dayOfMonth>9){
                                        String dateStr = year + "-0" + (month + 1) + "-" + dayOfMonth + " " + hourOfDay + ":" + minute + ":" + "00";
                                        dateView.setText(dateStr);
                                    }else if(month<=9&&dayOfMonth<=9){
                                        String dateStr = year + "-0" + (month + 1) + "-0" + dayOfMonth + " " + hourOfDay + ":" + minute + ":" + "00";
                                        dateView.setText(dateStr);
                                    }
                                }
                            }, Calendar.HOUR_OF_DAY, Calendar.MINUTE, true).show();
                        }, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.setOnCancelListener(dialog -> dateView.setText(""));
                datePickerDialog.show();
                break;
            }
            case R.id.keep_diary_location:
            case R.id.keep_diary_btn_location:{
                android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(KeepDiaryActivity.this);
                dialog.setTitle("所处位置");
                dialog.setMessage("暂时不支持读取地理位置，请手动输入");
                EditText editText = new EditText(KeepDiaryActivity.this);
                editText.setBackgroundResource(R.drawable.background_input);
                editText.setMinLines(4);
                editText.setMaxLines(4);
                editText.setGravity(Gravity.START);
                editText.setHint("空输入视为删除原有输入");
                editText.setPadding(30,10,30,10);
                dialog.setView(editText);
                dialog.setCancelable(false);
                dialog.setPositiveButton("添加", (dialog1, which) -> {
                    locationView.setText(editText.getText().toString());
                });
                dialog.setNegativeButton("取消",null);
                dialog.show();
                break;
            }
            default:
                break;
        }
    }
}